package com.bluepixel.tvitalia;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class ChannelListActivity extends Activity {

    // XML node keys
    static final String KEY_CATEGORY="channel";
    static final String KEY_TITLE="channelTitle";
    static final String KEY_DESC="channelDescr";
    static final String KEY_ID="channelId";
    static final String KEY_IMAGE="channelImg";

    private final ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String, Object>>();
    private final List<String> arrayChannelId=new ArrayList<String>();
    ChannelListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_channel_list);
	AdView adView=(AdView) this.findViewById(R.id.adViewChannel);
	adView.loadAd(new AdRequest());
	try {
	    Bundle extras=getIntent().getExtras();
	    populateWithXmlData(extras.getString(Utils.XML_TAG));
	}
	catch (IOException e) {
	    e.printStackTrace();
	}
	buildList();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.channel_list, menu);
	return true;
    }

    private void buildList() {
	ListView lv=(ListView) findViewById(R.id.channelListView);
	adapter=new ChannelListAdapter(this, data);
	lv.setAdapter(adapter);
	// listening to single listitem click
	lv.setOnItemClickListener(new OnItemClickListener() {
	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent i=new Intent(ChannelListActivity.this, VideoListActivity.class);
		i.putExtra(Utils.PLAYLIST_TAG, arrayChannelId.get(position));
		startActivity(i);
	    }
	});
    }

    private void populateWithXmlData(String xmlFileName) throws IOException {
	try {
	    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
	    DocumentBuilder db;
	    db=dbf.newDocumentBuilder();

	    InputStream is=getApplicationContext().getAssets().open(xmlFileName + ".xml");
	    Document doc=db.parse(is);
	    NodeList nl=doc.getElementsByTagName(KEY_CATEGORY);

	    // looping through all item nodes <item>
	    final XMLParser parser=new XMLParser();
	    for (int i=0; i < nl.getLength(); i++) {
		final Element e=(Element) nl.item(i);
		int imgResId=this.getResources().getIdentifier(parser.getValue(e, KEY_IMAGE).toLowerCase(), "drawable",
		    this.getPackageName());
		final Bitmap b=Utils.getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), imgResId), 25);
		data.add(new HashMap<String, Object>() {
		    {
			put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
			put(KEY_DESC, parser.getValue(e, KEY_DESC));
			put(KEY_IMAGE, b);
		    }
		});

		arrayChannelId.add(parser.getValue(e, KEY_ID));
	    }
	}
	catch (Exception e1) {
	    e1.printStackTrace();
	}
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.action_contatti:
		Intent email=new Intent(Intent.ACTION_SEND);
		email.putExtra(Intent.EXTRA_EMAIL, new String[]{getResources().getString(R.string.mail_to) });
		email.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.mail_subj));
		email.setType("message/rfc822");
		startActivity(Intent.createChooser(email, getResources().getString(R.string.action_contatti)));
		break;
	    case R.id.action_friend:
		Intent emailFriend=new Intent(Intent.ACTION_SEND);
		emailFriend.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.mail_friend_subj));
		emailFriend.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.mail_friend_text));
		emailFriend.setType("message/rfc822");
		startActivity(Intent.createChooser(emailFriend, getResources().getString(R.string.action_friend)));
		break;
	    case R.id.action_info:
		new AlertDialog.Builder(this)
		    .setTitle(getResources().getString(R.string.action_info))
		    .setMessage(getResources().getString(R.string.action_info_text))
		    .setPositiveButton(getResources().getString(R.string.btn_ok),
			new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			    }
			}).show();
		break;
	    case R.id.action_vote:
		Intent i=new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.action_vote_url)));
		startActivity(i);
		break;

	    default:
		break;
	}

	return true;
    }
}
